//
//  SETabBarController.swift
//  SmartEyeForPatient
//
//  Created by QDSG on 2021/4/2.
//

import UIKit

enum SETabBarItem: Int {
    case hospitalize, message, mine
    
    var controller: SEBaseViewController {
        switch self {
        case .hospitalize:
            return SEHospitalizeViewController()
        case .message:
            return SEMessageViewController()
        case .mine:
            return SEProfileViewController()
        }
    }
    
    var image: UIImage? {
        switch self {
        case .hospitalize: return #imageLiteral(resourceName: "tab_hospitalize")
        case .message:     return #imageLiteral(resourceName: "tab_message")
        case .mine:        return #imageLiteral(resourceName: "tab_mine")
        }
    }
    
    var selectedImage: UIImage? {
        switch self {
        case .hospitalize: return #imageLiteral(resourceName: "tab_hospitalize_selected")
        case .message:     return #imageLiteral(resourceName: "tab_message_selected")
        case .mine:        return #imageLiteral(resourceName: "tab_mine_selected")
        }
    }
    
    var title: String? {
        switch self {
        case .hospitalize: return "就诊"
        case .message:     return "消息"
        case .mine:        return "我的"
        }
    }
}

@objc class SETabBarController: UITabBarController {

    var meetingVc: XYMeetingViewController?

    override func viewDidLoad() {
        super.viewDidLoad()

        NemoSDK.sharedInstance().delegate = self
        
        UITabBar.appearance().barStyle = .default
        UITabBar.appearance().backgroundImage = UIColor.white.image()
        UITabBar.appearance().shadowImage = UIImage()
        UITabBar.appearance().tintColor =  Asset.main.color
        
        UITabBarItem.appearance().setTitleTextAttributes(
            [.foregroundColor: UIColor(hex: "#DAD5D5"), .font: UIFont.regular(12)],
            for: .normal
        )
        
        UITabBarItem.appearance().setTitleTextAttributes(
            [.foregroundColor: Asset.main.color, .font: UIFont.regular(12)],
            for: .selected
        )
        
        UITabBarItem.appearance().badgeColor = Asset.warn.color

        addChildController(tabBarItem: .hospitalize)
        addChildController(tabBarItem: .message)
        addChildController(tabBarItem: .mine)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        if !UserDefaults.authToken.isEmpty {
            SEIMManager.shared.connect()
            SEIMManager.shared.logoutMessageHandler = {
                (UIViewController.current as? SEBaseViewController)?.presentLoginViewController(selector: nil, handle: {
                    SEHUD.show(message: "已被踢下线")
                })
            }
        }
    }
    
    private func addChildController(tabBarItem: SETabBarItem) {
        let vc = tabBarItem.controller
        vc.navigationItem.title = tabBarItem.title
        vc.tabBarItem = UITabBarItem(title: tabBarItem.title,
                                     image: tabBarItem.image?.withRenderingMode(.alwaysOriginal),
                                     selectedImage: tabBarItem.selectedImage?.withRenderingMode(.alwaysOriginal))
        addChild(SENavigationController(rootViewController: vc))
    }

}

extension SETabBarController {
    override var preferredStatusBarStyle: UIStatusBarStyle {
        guard let selected = selectedViewController else { return .lightContent }
        return selected.preferredStatusBarStyle
    }
}

// MARK: - NemoSDK

extension SETabBarController {
    @objc func joinMeeting(_ account: String, _ displayName: String) {
        XYSDKManager.sharedInstance().joinMeeting(account, password: "")
        showMeetingUI(displayName)
    }

    private func showMeetingUI(_ displayName: String) {
        meetingVc = XYMeetingViewController()
        meetingVc?.displayName = displayName;
        meetingVc?.modalPresentationStyle = .overFullScreen
        meetingVc?.meeting(.connecting)
        present(meetingVc!, animated: true, completion: nil)
    }

}

// MARK: - NemoSDKDelegate

extension SETabBarController: NemoSDKDelegate {

    func loginResult(_ user: XYUser?, success: Bool) {
        if success {
            SEHUD.show(message: "xylink登录成功")
        } else {
            SEHUD.showError(message: "xylink登录失败")
        }
    }

    func nemoSDKDidCall(_ number: String, failed reason: NemoCallFailedReason) {
        var errorMsg = "呼叫失败"
        switch reason {
        case .alreadyInCall: errorMsg = "已经在呼叫中，不能重复呼叫"
        case .invalidNumber: errorMsg = "无效的号码"
        case .invalidPassword: errorMsg = "无效的密码"
        case .invalidSession: errorMsg = "无效的会话，禁止点会点呼叫自己"
        @unknown default: break
        }
        SEHUD.showError(message: errorMsg)
    }

    func nemoSDKDidCall(_ number: String, stateChanged callState: NemoCallState, reason: String) {
        AudioPlayerManager.sharedInstance.stop()
        meetingVc?.meeting(callState)
        switch callState {
        case .disConnected:
            SELog("xylink-----disConnected")
            meetingVc = nil
        case .connected:
            SELog("xylink-----connected")
        case .connecting:
            SELog("xylink-----connecting")
        @unknown default:
            break
        }
    }

    func nemoSDKDidRosterChanged(_ rosters: NemoRosters) {
        meetingVc?.rosterChanged(rosters)
    }

    func nemoSDKDidVideoChanged(_ videos: [NemoLayout]) {
        meetingVc?.videoViewLayout(videos)
    }

    func nemoSDKDidConferenceManagementStateChanged(_ type: NemoConferenceManagerManagementType, confMgmtInfo info: NemoConfMgmtInfo) {
        meetingVc?.meetingControlChanged(type, confMgmtInfo: info)
    }

    func nemoSDKWhiteboardDidStateChanged(_ remoteState: NemoWhiteboardRemoteState, reason: String) {
        meetingVc?.whiteboardStateChanged(remoteState)
    }

    func nemoSDKWhiteboardDidReceieved(_ remoteMessage: Any, type: NemoWhiteboardOperationState) {
        meetingVc?.whiteboardRemoteMessage(remoteMessage, type: type)
    }

    func contentShareStateChanged(_ type: NemoShareContentType, state: NemoShareContentState) {
        meetingVc?.contentShareStateChanged(type, state: state)
    }

    func nemoSDKDidUploadLogFileErrorInfo(_ errorInfo: String) {

    }

    func nemoSDKDidRecieveCaptionDisplay(_ captionInfo: NemoCaptionInfoModel) {
        meetingVc?.recieveCaption(captionInfo)
    }

    func nemoSDKDidDualStreamStateChanged(_ state: NemoDualState, reason: String) {
        meetingVc?.dualStreamStateChanged(state, reason: reason)
    }

    func nemoSDKDidRecordingStateChanged(_ start: Bool) {
        meetingVc?.recordingStateChanged(start)
    }

    func nemoSDKDidReceiveCall(_ number: String, displayName: String) {
        weak var weakSelf = self
        if !XYSDKManager.sharedInstance().isComingCallDispose() {
            AudioPlayerManager.sharedInstance.play()
            if let _ = weakSelf?.meetingVc  {
                XYSDKManager.sharedInstance().leaveMeeting()
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.0) {
                    weakSelf?.showMeetingUI(displayName)
                }
            } else {
                weakSelf?.showMeetingUI(displayName)
            }
        }
    }

}

// MARK: - AudioPlayerManager

class AudioPlayerManager: NSObject {
    static let sharedInstance = AudioPlayerManager()
    var audioPlayer: AVAudioPlayer?

    private func setSession(type: AVAudioSession.Category) -> Bool {
        let session = AVAudioSession.sharedInstance()
        var result = false

        do{
            try session.setCategory(type)
            result = true
        } catch let err{
            print("session设置类型失败:\(err.localizedDescription)")
            result = false
        }

        do {
            try session.setActive(true)
            result = true
        } catch let err {
            print("session初始化动作失败:\(err.localizedDescription)")
            result = false
        }

        return result
    }

    func play() {
        guard setSession(type: .playback) else { return }
        let path = Bundle.main.path(forResource: "ringing", ofType: "wav")!
        let url = URL(fileURLWithPath: path)
        do {
            audioPlayer = try AVAudioPlayer(contentsOf: url)
            audioPlayer?.numberOfLoops = -1
            audioPlayer?.prepareToPlay()
        } catch let err {
            print("audioPlayer初始化动作失败:\(err.localizedDescription)")
        }
        audioPlayer?.play()
    }

    func stop() {
        guard audioPlayer != nil else { return }
        audioPlayer?.stop()
        audioPlayer = nil
    }

}
